﻿using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;

namespace MangoMes.Write.API.Applications.Clientss
{
    public class ClientManagementListHandler : IRequestHandler<ClientManagementListCommand, PageDTO<ClientManagementDTO>>
    {
        private readonly IBateRepository<ClientManagementDTO> dto;
        public ClientManagementListHandler(IBateRepository<ClientManagementDTO> dto)
        {
            this.dto = dto; 
        }
        /// <summary>
        /// 客户查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PageDTO<ClientManagementDTO>> Handle(ClientManagementListCommand request, CancellationToken cancellationToken)
        {
            PageDTO<ClientManagementDTO> pageDTO=new PageDTO<ClientManagementDTO>();
            var pageNum = (request.pageIndex - 1)*request.pageSize;
            ClientManagementDTO clientDTO=new ClientManagementDTO();
            //连接数据库
            DapperHelper dapperHelper = new DapperHelper();
            string conn = dapperHelper.MangoMesWrite;
            string sql = "SELECT * FROM clientmanagement inner join clienttype on " +
                "clientmanagement.ClientTypeId=clienttype.ClientTypeId where clientmanagement.IsNo = 0 ";
            var result=dto.GetAll(sql, clientDTO, conn).ToList();
            if (!string.IsNullOrEmpty(request .ClientNo))
            {
                result =result .Where(x => x.ClientNo==request.ClientNo).ToList();
            }
            if (!string.IsNullOrEmpty(request.ClientName ))
            {
                result = result.Where(x => x.ClientName.Contains(request.ClientNo)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ClientAName ))
            {
                result = result.Where(x => x.ClientAName == request.ClientAName).ToList();
            }
            if (!string.IsNullOrEmpty(request.ClientEname ))
            {
                result = result.Where(x => x.ClientEname == request.ClientEname).ToList();
            }
            if (request.IsVaild  > -1)
            {
                result = result.Where(p => p.IsVaild == request.IsVaild).ToList();
            }

            pageDTO.TotalCount=result.Count();
            pageDTO.PageCount = (int)Math.Ceiling(result.Count() * 1.0 / request.pageSize);
            result = result.OrderByDescending(x=>x.ClientId).Skip((request.pageIndex - 1)*request.pageSize).Take(request.pageSize).ToList();
            pageDTO.Data = result;
            return pageDTO;
        }
    }
}
